use anyhow::Result;
use clap::Parser;
use tracing::{level_filters::LevelFilter, debug};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, fmt::Layer, Layer as _};
use chat_server::{AppConfig, get_router};


#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
pub struct CmdArgs {
    #[arg(short, long)]
    pub config: String
}
// const WIN_CONFIG_PATH: &'static str = "E:\\code\\rust\\chat\\chat_server\\app.yaml";
// const MAC_CONFIG_PATH: &'static str = "/Users/cuixuecheng/Documents/code/rust/chat/chat_server/app.yaml";

#[tokio::main]
async fn main() -> Result<()> {
    // std::env::set_var("CHAT_CONFIG", CONFIG_PATH);
    let args = CmdArgs::parse();

    // tracing_subscriber::fmt
    // ::init();
    let layer = Layer::new().with_filter(LevelFilter::INFO);
    tracing_subscriber::registry().with(layer).init();

    debug!("args config: {}", args.config);
    let config = AppConfig::load(args.config)?;
    let addr = format!("{}:{}", config.server.host, config.server.port);

    debug!("addr: {}", addr);

    let app = get_router(config).await?;

    let listener = tokio::net::TcpListener::bind(&addr).await?;

    axum::serve(listener, app.into_make_service()).await?;

    Ok(())
}